<template>
  <div class='page grey-stage workbench'>
    <top-filter :filterOptions="filterOptions" @change-filter="changeFilterValue" ref="topFilter"></top-filter>
    <crm-cover v-if="isShowCover" :hideOnBlur="false"></crm-cover>
    <div
    class="scroll-container"
    :style="{
      'padding-top': this.scrollerTop + 'px',
      'height': this.scrollerHeight + 'px',
      'width': this.winWidth + 'px'
    }"
    >
      <section
      class="workb-section"
      v-for="(value, id) in workbenchData"
      :key="id">
        <h3 class="target-title"><template v-if="targetTitle" >{{ getTargetTitle(type, value) }}</template></h3>
        <my-target
        :id="id"
        :suid="user.id"
        :type="type"
        :barTitle="getTargetTitle(type) + '目标'"
        :values="value.target" />

        <team-analyze
        :id="id"
        :time="timeStamp"
        :list="value.list"
        v-if="type === 'team'"
        class="section-style" />

        <company-analyze
        :id="id"
        :time="timeStamp"
        :list="value.list"
        v-if="type === 'company'"
        class="section-style" />

        <bulletin
        :id="id"
        :suid="user.id"
        :type="type"
        :time="timeStamp"
        :values="value.sales_brief"
        class="section-style" />

        <transaction
        :id="id"
        :suid="user.id"
        :type="type"
        :time="timeStamp"
        :values="value.transaction"
        class="section-style" />

        <prediction
        :id="id"
        :suid="user.id"
        :type="type"
        :time="timeStamp"
        :values="value.prediction"
        class="section-style" />

        <NewCustom
          :id="id"
          :suid="user.id"
          :type="type"
          :time="timeStamp"
          :values="value.new_custom"
          v-if="type === 'my'"
          class="section-style" />

      </section>
    </div>
    <crm-tabbar v-if="!isAppMode" activeItem='workbench' ref="tabbar"></crm-tabbar>
  </div>
</template>

<script>
import crmTabbar from '../components/crm-tabbar'
import topFilter from '../components/top-filter'
import MyTarget from '../components/my-target'
import Transaction from '../components/transaction'
import Bulletin from '../components/bulletin'
import TitleBar from '../components/title-bar'
import TextGrid from '../components/TextGrid/grid'
import GridItem from '../components/TextGrid/grid-item'
import TeamAnalyze from '../components/team-analyze'
import CompanyAnalyze from '../components/company-analyze'
import Prediction from '../components/prediction'
import NewCustom from '../components/new-custom'

import Q from 'q'
import crmCover from '../components/crm-cover'
import { mapState, mapActions } from 'vuex'

import { timeOpts } from '../lib/options/time'

const MY = 'my'
const TEAM = 'team'
const COMPANY = 'company'
const TITLE_MY = '我的'

export default {
  data () {
    return {
      COMPANY: COMPANY,
      TEAM: TEAM,
      MY: MY,
      bulletinData: {},
      scrollerTop: '',
      scrollerHeight: '',
      winWidth: '',
      winWidth: '',
      filterData: '',
      morePath: '/',
      barTitle: '我的目标',
      targetTitle: TITLE_MY,
      teamName: '',
      morePath: '/',
      dealMorePath: '/',
      targetData: {},
      salesBriefData: {},
      transationData: {},
      timeStamp: '',
      workbenchData: {},
      type: '',
      yearsCount: 3, // 可以查{ yearsCount }年的数据
      filterOptions: [],
    }
  },
  components: {
    topFilter,
    crmCover,
    crmTabbar,
    MyTarget,
    TextGrid,
    GridItem,
    TitleBar,
    Bulletin,
    TeamAnalyze,
    CompanyAnalyze,
    Transaction,
    Prediction,
    NewCustom
  },
  beforeMount () {
    this.initData()
  },
  mounted () {
    this.callJsApi('biz.navigation.setTitle', { title: '工作台' })
    this.$nextTick(() => {
      this.caculateScroller()
    })
  },
  watch: {
    windowSize (size) {
      this.caculateScroller()
    }
  },
  computed: {
    ...mapState({
      isShowCover: state => state.app.isShowCover,
      totalTarget: state => state.app.target,
      user: state => state.app.user,
      windowSize: state => state.app.windowSize,
      isAppMode: state => state.config.isAppMode
    })
  },
  methods: {
    getTargetOpts (type) {
      let option

      if (this.user.is_manager == 1 || this.user.is_system_manager == 1) {
        option = [
          {
            text: '我的',
            value: 'my'
          },
          {
            text: '团队',
            value: 'team'
          },
          {
            text: '公司',
            value: 'company'
          }
        ]
      } else if (this.user.is_team_manager == 1) {
        option = [
          {
            text: '我的',
            value: 'my'
          },
          {
            text: '团队',
            value: 'team'
          }
        ]
      } else {
        option = [
          {
            text: '我的',
            value: 'my'
          }
        ]
      }
      return {
        title: this.getTargetTitle(type || MY),
        class: 'txt-center',
        value: type,
        name: 'type',
        checked: type,
        options: option
      }
    },
    initOptions (data) {
      data = data || {}
      this.filterOptions = []
      const targetOpts = this.getTargetOpts(data.type)
      const timeOpts = this.getTimeOpts(data.timestamp)
      this.filterOptions = [
        targetOpts,
        timeOpts
      ]
      this.$nextTick(() => {
        const filterData = this.$refs.topFilter.getData()
        this.timeStamp = this.getTimestampByFilterData(filterData)
      })
    },
    getTimestampByFilterData(filterData) {
      const filterDate = new Date()
      filterDate.setFullYear(filterData.year.value)
      filterDate.setMonth(filterData.year.data[0].value - 1)
      return filterDate.getTime()
    },
    initData () {
      const defaultParams = this.getDefaultParam()
      this.timeStamp =  defaultParams.time
      this.initOptions({
        type: defaultParams.type
      })
      this.type = defaultParams.type
      this.$getWorckbenchData(defaultParams)
    },
    $getWorckbenchData (defaultParams) {
      this.$vux.loading.show()
      this.getWorckbenchData(defaultParams)
      .then((response) => {
        if (response.data.errcode === 0) {
          const results = response.data.results
          this.workbenchData = results
          this.$vux.loading.hide()
        }
      }).catch(() => {
        this.$vux.loading.hide()
      })
    },
    getTargetTitle (type, value) {
      let targetTitle = ''
      switch (type) {
        case MY:
          targetTitle = value && value.team_name ? value.team_name : TITLE_MY
          break
        case TEAM:
          targetTitle = value ? value.team_name : '团队'
          break
        case COMPANY:
          targetTitle = '公司'
          break
      }
      return targetTitle
    },
    changeFilterValue (filterOptions, filterData) {
      if (this.filterData !== filterData) {
        const filterDate = new Date()
        filterDate.setFullYear(filterData.year.value)
        filterDate.setMonth(filterData.year.data[0].value - 1)

        var submitData = Object.assign({}, this.filterData, {
          'timestamp': this.getTimestamp(filterDate),
          'type': filterData.type
        })
        this.initOptions({
          'timestamp': filterDate.getTime(),
          'type': filterData.type
        })
        this.timeStamp = filterDate.getTime()
        this.$getWorckbenchData(submitData)
        this.type = filterData.type
        let originalFilterData = this.filterData
        this.filterData = submitData
      }
    },
    getDefaultParam () {
      const dateObj = new Date()
      return {
        type: MY,
        time: dateObj.getTime(),
        timestamp: this.getTimestamp(dateObj)
      }
    },
    getTimestamp(dateObject) {
      let currentYear = dateObject.getFullYear()
      let currentMonth = dateObject.getMonth()
      let currentMonthDate = new Date(currentYear, currentMonth)
      return Math.floor(currentMonthDate.getTime() / 1000)
    },
    getTimeOpts: timeOpts,
    caculateScroller () {
      const winHeight = window.innerHeight
      const filterHeight = this.$refs['topFilter'].$el.offsetHeight
      const tabbarHeight = this.$refs['tabbar'] ? this.$refs['tabbar'].$el.offsetHeight : 0;
      this.scrollerTop = filterHeight
      this.scrollerHeight = winHeight - filterHeight
      if (!this.isAppMode) {
        this.scrollerHeight = this.scrollerHeight - tabbarHeight
      }
      this.winWidth = window.innerWidth;
    },
    ...mapActions({
      getWorckbenchData: 'getWorckbenchData'
    })
  },

}
</script>

<style lang="less">
.workbench {
  .target-title {
    // margin-top: 42px;
    padding: 15px;
    text-align: center;
  }

  .section-style {
    margin-top: 15px;
    background-color: white;
  }

  .workb-section {
    background-color: rgba(0, 0, 0, 0)
  }

  .business-wrapper {

  }
}
</style>
